const sqlite = require('sqlite3');

const db = new sqlite.Database("./database.db")

db.on('open', function () {
    console.log('database open success!');
})

db.on('error', function (err) {
    console.log(err);
})


async function run(sql, params) {
    return new Promise(function (resolve, reject) {
        db.run(sql, params || [], function (err) {
            if (err) {
                return reject(err);
            }
            return resolve(this);
        })
    })
}

exports.run = run;

async function all(sql, params) {
    return new Promise(function (resolve, reject) {
        db.all(sql, params || [], function (err, rows) {
            if (err) {
                return reject(err);
            }
            return resolve(rows);
        })
    })
}

async function exec(sql) {
    return new Promise(function (resolve, reject) {
        db.exec(sql, function (err) {
            if (err) {
                return reject(err);
            }
            return resolve(this);
        })
    })
}


async function getAllCategoryCarousel(id) {
    return await all('select * from category_carousel where cate_id=?', [id]);
}

exports.getAllCategoryCarousel = getAllCategoryCarousel;

const create_category_carousel_table = `
CREATE TABLE if not exists "category_carousel" (
    "id" integer primary key autoincrement,
    "cate_id" integer,
    "file"  text
);
`;
async function init() {
    const r = await run(create_category_carousel_table);
    console.log(r);
}

exports.init = init;

async function insertCategoryCarousel(cate_id, urlPath){
    return await run("insert into category_carousel(cate_id,file) values($cate_id,$file)", {
        $cate_id: cate_id,
        $file: urlPath,
        // $file: '/public/img/1.jpg',
    });
}
exports.insertCategoryCarousel = insertCategoryCarousel;

async function deleteCategoryCarousel(id) {
    return await run('delete from category_carousel where id=?', [id]);
}

exports.deleteCategoryCarousel = deleteCategoryCarousel;